/*<![CDATA[*/
var popBox = (function() {
    if (!window.console) {
        window.console = {
            log: function(msg) {
            }
        }
    }
    //绑定加载事件
    function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) {
                    oldonload();
                }
                func();
            }
        }
    }

    addLoadEvent(function() {
        popBox.init();
    })

    //if ie6
    var ie6 = /msie 6.0/.test(window.navigator.userAgent.toLowerCase());
    var ie = !!document.all;
    var db = document.documentElement || document.body;

    function camelize(s) {
        return s.replace(/-(\w)/g, function(strMatch, p1) {
            return p1.toUpperCase();
        });
    }

    /*--- Browser ---*/
    function getBrowserSize() {
        return {
            'width': Math.max(Math.max(db.scrollWidth, db.offsetWidth), db.clientWidth),
            'height': Math.max(Math.max(db.scrollHeight, db.offsetHeight), db.clientHeight)
        }
    }

    /*--- Ajax ---*/
    var XHR = function() {
        function createXhrObject() {
            var method = [
			  function() { return new XMLHttpRequest() },
			  function() { return new ActiveXObject("Msxml2.XMLHTTP") },
			  function() { return new ActiveXObject("Microsoft.XMLHTTP") }
			];

            for (var i = 0, len = method.length; i < len; i++) {
                try {
                    method[i]();
                } catch (e) {
                    continue;
                }
                createXhrObject = method[i];
                return method[i]();
            }
        }

        return {
            'request': function(url, callback, postData) {
                var xhr = createXhrObject();
                if (!xhr) return;
                var method = (postData) ? "POST" : "GET";
                url += (url.indexOf('?') > 0 ? '&' : '?');
                url += ('rnd=' + Math.random());
                xhr.open(method, url, true);
                xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
                if (postData) {
                    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                }
                xhr.onreadystatechange = function() {
                    if (xhr.readyState != 4) return;
                    callback(xhr);
                }
                if (xhr.readyState == 4) return;
                xhr.send(postData);
            }
        }
    } ();

    /*--- 事件 ---*/
    var Event = {
        'add': function(obj, type, fn) {
            if (obj.addEventListener)
                obj.addEventListener(type, fn, false);
            else if (obj.attachEvent)
                obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event)); });
        },
        'remove': function(obj, evType, fn, useCapture) {
            if (obj.removeEventListener) {
                obj.removeEventListener(evType, fn, useCapture);
                return true;
            } else if (obj.detachEvent) {
                var r = obj.detachEvent('on' + evType, fn);
                return r;
            } else {
                obj['on' + evType] = fn;
            }
        },
        'get': function() {
            if (document.all) return window.event;
            func = Event.get.caller;
            while (func != null) {
                var arg0 = func.arguments[0];
                if (arg0) {
                    if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                        return arg0;
                    }
                }
                func = func.caller;
            }
            return null;
        },
        //阻止默认动作
        'stopDefault': function(e) {
            if (e && e.preventDefault)
                e.preventDefault();
            else
                window.event.returnValue = false;
            return false;
        }
    }

    //重置pop位置
    function setPosition(elem) {
        var width = elem.offsetWidth, height = elem.offsetHeight;
        elem.style.marginTop = -(height / 2) + 'px';
        elem.style.marginLeft = -(width / 2) + 'px';
    }

    /*--- DOM ---*/
    var DOM = {
        '$': function(elem) {
            return typeof elem == 'string' ? document.getElementById(elem) : elem;
        },
        //通过className查找元素
        'getElementsByClass': function(name, tag, parent) {
            if (!name) return;
            parent = parent || document,
			tag = tag || '*';
            var ret = [],
				re = new RegExp('(|\\s)' + name + '(\\s|$)'),
				elems = parent.getElementsByTagName(tag);
            for (var i = 0; i < elems.length; i++) {
                var elem = elems[i];
                if (re.test(elem.className)) {
                    ret.push(elem);
                }
            }
            return ret;
        },
        'find': {
            'sibling': function(n, elem) {
                return DOM.siblingChild(n, elem);
            },
            'first': function(elem) {
                return DOM.firstChild(elem);
            },
            'next': function(elem) {
                return DOM.nextChild(elem);
            }
        },
        //查找子元素
        'siblingChild': function(n, elem) {
            var ret = [];
            for (; n; n = n.nextSibling) {
                if (n.nodeType == 1 && n != elem)
                    ret.push(n);
            }
            return ret;
        },
        //返回元素的第一个子元素
        'firstChild': function(elem) {
            elem = elem.firstChild;
            return elem && elem.nodeType != 1 ?
				nextChild(elem) : elem;
        },
        //查找元素的后一个兄弟元素
        'nextChild': function(elem) {
            do {
                elem = elem.nextSibling;
            } while (elem && elem.nodeType != 1);
            return elem;
        },
        //设置样式
        'setStyle': function(elem, styles) {
            if (!(element = DOM.$(elem))) return false;
            for (var name in styles) {
                if (!styles.hasOwnProperty(name)) {
                    continue;
                }
                var value = styles[name];
                if (name == 'opacity' && ie) {
                    element.style.filter = 'alpha(opacity=' + value * 100 + ')';
                } else if (name == 'float') {
                    element.style[ie ? 'styleFloat' : 'cssFloat'] = value;
                } else {
                    element.style[camelize(name)] = value;
                }
            }
        },
        //from thickbox
        'getParam': function(param) {
            var Params = {};
            if (!param) { return Params; } // return empty object
            var Pairs = param.split(/[;&]/);
            for (var i = 0; i < Pairs.length; i++) {
                var KeyVal = Pairs[i].split('=');
                if (!KeyVal || KeyVal.length != 2) { continue; }
                var key = unescape(KeyVal[0]);
                var val = unescape(KeyVal[1]);
                val = val.replace(/\+/g, ' ');
                Params[key] = val;
            }
            return Params;
        }
    }

    /*--- pop ---*/
    var popMask, popMain;
    var prop, href, rel;
    var type, width, height;
    //初始化pop
    var Pop = {
        //初始化参数
        'init': function(e) {
            href = this.href;
            rel = this.rel;
            if (!href || !rel) return;
            Pop.create(e);
        },
        //创建遮罩层
        'mask': function() {
            var browserSize = getBrowserSize();
            console.log(browserSize.width + ',' + browserSize.height);
            popMask = document.createElement('div');
            popMask.id = 'pop-mask';
            DOM.setStyle(popMask, {
                'position': 'absolute',
                'left': 0,
                'top': 0,
                'width': '100%',
                'height': browserSize.height + 'px',
                'background': '#000000',
                'opacity': 0.5,
				'zIndex': 99
            });
            document.body.appendChild(popMask);

            /* for IE6 */
            if (ie6) {
                var tmpIframe = document.createElement('iframe');
                tmpIframe.id = 'pop-iframe';
                DOM.setStyle(tmpIframe, {
                    'position': 'absolute',
                    'left': 0,
                    'top': 0,
                    'width': '100%',
                    'height': '100%',
                    'opacity': 0
                });
                popMask.appendChild(tmpIframe);
            }
        },
        //创建pop主体层
        'main': function() {
            //如果不存在则创建
            !popMask && Pop.mask() || (popMask.style.display = 'block');
            if (!popMain) {
                popMain = document.createElement('div');
                popMain.id = 'pop-main';
                DOM.setStyle(popMain, {
                    'position': 'fixed',
                    'left': '50%',
                    'top': '50%',
                    'zIndex': 100
                });
                document.body.appendChild(popMain);
            } else {
                popMain.style.display = 'block';
            }
        },
        'create': function(e) {
            Pop.main();
            prop = DOM.getParam(rel) || {};
            prop.type && (type = prop.type),
			width = prop.width || 300,
			height = prop.height || 200,
			prop.callback && (Call.callback = eval(prop.callback));
            Call[type] && Call[type](this);

            //ie6不支持fixed, 用定时器让pop始终显示在窗口中间
            if (ie6) {
                DOM.setStyle(popMain, { 'position': 'absolute' });
                (function() {
                    if (popMain && (popMain.style.display != 'none')) {
                        DOM.setStyle(popMain, {
                            'top': db.scrollTop + (db.clientHeight / 2) + 'px'
                        });
                        setTimeout(arguments.callee, 100);
                    }
                })();
            }

            //设置pop主体位置
            setPosition(popMain);
            //Event.addEvent(window, 'resize', Pop.resize);

            //阻止默认事件
            !e && (e = Event.get());
            e && Event.stopDefault(e);
        },
        'closeInit': function(parent, callback) {
            callback = callback || popBox.close;
            var close = DOM.getElementsByClass('close', '*', parent);
            if (close.length > 0) {
                for (var i = 0; i < close.length; i++) {
                    close[i].style.display = 'inline-block';
                    Event.add(close[i], 'click', callback);
                }
            }
            //Event.removeEvent(window, 'resize', Pop.resize);
        }
        /*
        'resize': function() {
        if (d.clientHeight <= popMain.offsetHeight) {
        DOM.setStyle(popMain, {'top':0, 'marginTop':0});
        } else {
        DOM.setStyle(popMain, {'top': '50%'});
        setPosition(popMain);
        }
        }*/
    }

    //调用指定pop类型
    var Call = {
        //iframe调用
        'iframe': function() {
            popMain.innerHTML = '<iframe src="' + href + '" scrolling="no" frameborder="0" width="' + width + '" height="' + height + '" allowtransparency=true></iframe>';
            var iframe = popMain.getElementsByTagName('iframe')[0];
            iframe && (iframe.onload = iframe.onreadystatechange = function() {
                var iframeContext = iframe.contentDocument || iframe.contentWindow.document;
                if (this.readyState && this.readyState == 'complete' || this.readyState == undefined) {
                    Pop.closeInit(iframeContext)
                    Call.callback && Call.callback(iframeContext);
                }
            });
        },
        //ajax调用
        'ajax': function() {
            function process(re) {
                var temp = document.createElement('div');
                temp.innerHTML = re.responseText;
                var tempPop = DOM.getElementsByClass('tempBox', 'div', temp);
                if (tempPop.length > 0) {
                    popMain.innerHTML = tempPop[0].innerHTML
                } else {
                    tempPop = document.createElement('div');
                    tempPop.appendChild(temp.getElementsByTagName('div')[0]);
                    popMain.innerHTML = tempPop.innerHTML
                }
                Pop.closeInit(popMain);
                Call.callback && Call.callback(popMain);
                setPosition(popMain);
            }
            XHR.request(href, process)
        },
        //内联元素调用
        'inline': function() {
            var index, id, temp, inlineObj, inlineParent;
            index = href.indexOf('#');
            if (index != -1) {
                id = href.substring(index + 1);
                inlineObj = DOM.$(id);
                if (!inlineObj) {
                    popBox.close();
                    alert('找不到 ID 为 ' + id + ' 的元素');
                    return false;
                }
                inlineParent = inlineObj.parentNode;
                inlineObj.style.display = 'block';
                temp = document.createElement('div');
                temp.appendChild(inlineObj);
                popMain && (popMain.innerHTML = temp.innerHTML);
                Pop.closeInit(popMain, function(e) {
                    inlineObj.style.display = 'none';
                    inlineParent.appendChild(inlineObj);
                    popBox.close(e);
                });
                Call.callback && Call.callback(popMain);
            } else {
                popBox.close();
                return false;
            }
        },
        //关闭pop
        'close': function(e) {
            
     
                popMask.style.display = 'none';
                popMain.innerHTML = '';
                popMain.style.display = 'none';
                Call.callback = null;
                e && Event.stopDefault(e);

            
            
        }
    }

    return {
        'init': function(parent) {
            var popElems = DOM.getElementsByClass('ipopBox', 'a', parent);
            for (var i = 0, len = popElems.length; i < len; i++) {
                Event.add(popElems[i], 'click', Pop.init);
            }
            Event.add(window, 'resize', function() {
                var mask = DOM.$('pop-mask');
                if (mask) {
                    var browserSize = getBrowserSize();
                    mask.style.height = browserSize.height + 'px';
                }
            })
        },
        //为类型iframe的pop关闭链接留的接口
        'close': function(e) {
            return Call.close(e);
        },
        'show': function(h, r, f) {      
            href = h, rel = r;
            f && (Call.callback = f);
            Pop.create();
        }
    }
})();
/*]]>*/

